package com.mallcai.bigdata.ladon.utils;

import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Consumer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * @author feixy
 * @version 1.0
 * @date 2019-07-18 15:14
 */
public class SqlUtils {

    public static final Pattern PARAM_NAME_PATTERN = Pattern.compile("#([_a-zA-Z][-_a-zA-Z0-9]*)#|(:[_a-zA-Z][-_a-zA-Z0-9]*)",Pattern.MULTILINE);

    public static final Pattern SINGLE_PARAM_NAME_PATTERN = Pattern.compile("^#([_a-zA-Z][-_a-zA-Z0-9]*)#$");

    /**
     * 解析sql中的参数
     * @param sql
     * @return
     */
    public static List<String> parseParamName(String sql){
        List<String> ans = new ArrayList<>();
        collectParamName(sql, ans::add);
        return ans;
    }

    private static void collectParamName(String sql, Consumer<String> consumer) {
        if(StringUtils.isNotEmpty(sql)){
            Matcher matcher = PARAM_NAME_PATTERN.matcher(sql);
            while(matcher.find()){
                String ans = matcher.group(1);
                if(StringUtils.isEmpty(ans)){
                    ans = matcher.group(2);
                }
                consumer.accept(ans);
            }
        }
    }

    /**
     * 解析sql中的参数,过滤重复
     * @param sql
     * @return
     */
    public static Set<String> parseUniqueParamName(String sql){
        Set<String> ans = new HashSet<>();
        collectParamName(sql, ans::add);
        return ans;
    }

}
